// import { invoke } from '@tauri-apps/api/core';
import { useState } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import { mkdir, exists } from '@tauri-apps/plugin-fs';
import { Command } from '@tauri-apps/plugin-shell';
import { Button, message, Select, Slider } from 'antd';
import { Header } from '@/components';
import { getFileDir, getFileName } from '@/utils';

enum FileType {
  PNG = 'png',
  JPG = 'jpg',
  WEBP = 'webp',
}

export default function Avifdec() {
  const [loading, setLoading] = useState(false);
  const [totalTime, setTotalTime] = useState(0);
  const [quality, setQuality] = useState(90);
  const [compressLevel, setCompressLevel] = useState(9);
  const [targetType, setTargetType] = useState<FileType>(FileType.JPG);

  async function decodeFile() {
    try {
      setTotalTime(0);
      setLoading(true);
      // invoke('open_file', { invokeMessage: 'Hello!' });
      const files: any[] | null = await open({
        multiple: true,
        directory: false,
      });

      if (!files || files.length == 0) return;
      const start = Date.now();
      const fileDir = getFileDir(files[0]);
      const isExists = await exists(`${fileDir}/result`);
      if (!isExists) await mkdir(`${fileDir}/result`);
      let hasErr = false,
        msg = '';
      const shellParams: string[] = [];

      if (targetType === FileType.JPG) {
      }
      switch (targetType) {
        case FileType.JPG:
          shellParams.push('-q', quality.toString());
          break;
        case FileType.PNG:
          shellParams.push('--png-compress', compressLevel.toString());
          break;
        default:
          shellParams.push('--png-compress', '9');
          break;
      }

      await Promise.all(
        files.map(async (item) => {
          const fileName = getFileName(item);
          const command = Command.sidecar('binaries/avifdec', [
            ...shellParams,
            item,
            `${fileDir}/result/${fileName?.split('.')[0]}.${targetType}`,
          ]);

          const output = await command.execute();
          if (output?.code !== 0) {
            hasErr = true;
            msg = output.stderr;
          }
        }),
      );
      if (hasErr) message.error({ content: msg });
      setTotalTime(Date.now() - start);
    } catch (e: any) {
      console.log(e);
      message.error(e.message);
    } finally {
      setLoading(false);
    }
  }

  const renderOptions = () => {
    if (targetType === FileType.JPG)
      return (
        <>
          <div className="mt-8 text-[16px] font-bold">质量：{quality}</div>
          <Slider
            className="mt-4 w-[300px]"
            value={quality}
            onChange={(value) => setQuality(value)}
            min={0}
            max={100}
          />
        </>
      );

    if (targetType === FileType.PNG) {
      return (
        <>
          <div className="mt-8 text-[16px] font-bold">压缩等级：{compressLevel}</div>
          <Slider
            className="mt-4 w-[300px]"
            value={compressLevel}
            onChange={(value) => setCompressLevel(value)}
            min={0}
            max={9}
          />
        </>
      );
    }
  };

  return (
    <div className="relative h-full w-full p-4">
      <Header title="avif解码" />
      <div className="mt-8 text-[16px] font-bold">图片格式: {targetType}</div>
      <Select
        className="mt-4 w-[300px]"
        options={[
          { label: 'png', value: 'png' },
          { label: 'jpg', value: 'jpg' },
          // { label: 'webp', value: 'webp' },
        ]}
        value={targetType}
        onChange={(value) => setTargetType(value)}
      ></Select>

      {renderOptions()}
      <div className="mt-8 flex border-collapse flex-row items-center gap-5 rounded-lg border px-4 py-4">
        <div className="text-[16px] font-bold">耗时：{totalTime}ms</div>
        <Button className="h-[40px] w-[150px] border" loading={loading} onClick={decodeFile}>
          选择文件
        </Button>
      </div>
    </div>
  );
}
